using B.S.Domain.InvoiceManagement;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;

namespace B.S.Data.MES.API.Applications.B.S.KApplications.Command.InvoiceCommand
{
    /// <summary>
    /// 更新销售发票命令处理程序
    /// 处理销售发票的更新逻辑
    /// </summary>
    public class UpdateSalesInvoiceCommandHandler : IRequestHandler<UpdateSalesInvoiceCommand, APIRequst<bool>>
    {
        private readonly IBaseRepository<SalesInvoice> _salesInvoiceRepository;
        private readonly IBaseRepository<SalesInvoiceDetail> _salesInvoiceDetailRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="salesInvoiceRepository">销售发票仓储</param>
        /// <param name="salesInvoiceDetailRepository">销售发票明细仓储</param>
        public UpdateSalesInvoiceCommandHandler(IBaseRepository<SalesInvoice> salesInvoiceRepository, IBaseRepository<SalesInvoiceDetail> salesInvoiceDetailRepository)
        {
            _salesInvoiceRepository = salesInvoiceRepository;
            _salesInvoiceDetailRepository = salesInvoiceDetailRepository;
        }

        /// <summary>
        /// 处理更新销售发票的命令
        /// </summary>
        /// <param name="request">更新销售发票命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果，成功时Code为成功，Data为true，失败时返回错误信息</returns>
        public async Task<APIRequst<bool>> Handle(UpdateSalesInvoiceCommand request, CancellationToken cancellationToken)
        {
            using ( var tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    // 验证参数
                    if (request.InvoiceId <= 0)
                    {
                        return new APIRequst<bool> { Code = RequstCode.失败, Msg = "发票ID不能为空" };
                    }

                    if (string.IsNullOrEmpty(request.InvoiceNo))
                    {
                        return new APIRequst<bool> { Code = RequstCode.失败, Msg = "发票编号不能为空" };
                    }

                    // 查询发票信息
                    var salesInvoice = await _salesInvoiceRepository.GetAll().FirstOrDefaultAsync(a => a.InvoiceId == request.InvoiceId);
                    if (salesInvoice == null || salesInvoice.isDel)
                    {
                        return new APIRequst<bool> { Code = RequstCode.失败, Msg = "发票不存在或已被删除" };
                    }

                    // 更新发票主表信息
                    salesInvoice.InvoiceNo = request.InvoiceNo;
                    salesInvoice.OrderId = request.OrderId;
                    salesInvoice.CustomerId = request.CustomerId;
                    salesInvoice.InvoiceAmount = request.InvoiceAmount;
                    salesInvoice.InvoiceDate = request.InvoiceDate;
                    salesInvoice.InvoiceType = request.InvoiceType;
                    salesInvoice.InvoiceStatus = request.InvoiceStatus;
                    salesInvoice.TaxRate = request.TaxRate;
                    salesInvoice.TaxAmount = request.TaxAmount;
                    salesInvoice.SubtotalAmount = request.SubtotalAmount;
                    salesInvoice.Remarks = request.Remarks;
                    salesInvoice.UpdateName = request.UpdateName;
                    salesInvoice.UpdateTime = DateTime.Now;

                    // 保存发票主表更新
                    var updateResult = await _salesInvoiceRepository.Update(salesInvoice);
                    if (updateResult <= 0)
                    {
                        return new APIRequst<bool> { Code = RequstCode.失败, Msg = "发票主表更新失败" };
                    }

                    // 处理发票明细
                    if (request.InvoiceDetails != null && request.InvoiceDetails.Count > 0)
                    {
                        // 获取当前发票的所有明细
                        var existingDetails = (await _salesInvoiceDetailRepository.GetAll().Where(d => d.InvoiceId == request.InvoiceId && !d.isDel).ToListAsync());

                        // 用于存储需要批量处理的明细
                        var detailsToUpdate = new List<SalesInvoiceDetail>();
                        var detailsToAdd = new List<SalesInvoiceDetail>();

                        // 遍历请求中的明细
                        foreach (var detailDto in request.InvoiceDetails)
                        {
                            if (detailDto.DetailId > 0)
                            {
                                // 更新已有明细
                                // 修正：使用DetailId匹配，而不是InvoiceId
                                var existingDetail = existingDetails.FirstOrDefault(d => d.DetailId == detailDto.DetailId);
                                if (existingDetail != null)
                                {
                                    if (detailDto.IsDelete)
                                    {
                                        // 删除明细（软删除）
                                        existingDetail.isDel = true;
                                        existingDetail.UpdateTime = DateTime.Now;
                                        existingDetail.DeleteName = request.UpdateName;
                                        existingDetail.DeleteTime = DateTime.Now;
                                        detailsToUpdate.Add(existingDetail);
                                    }
                                    else
                                    {
                                        // 更新明细信息
                                        existingDetail.ProductName = detailDto.ProductName;
                                        existingDetail.Specifications = detailDto.Specification;
                                        existingDetail.Unit = detailDto.Unit;
                                        existingDetail.Quantity = detailDto.Quantity;
                                        existingDetail.UnitPrice = detailDto.UnitPrice;
                                        existingDetail.Amount = detailDto.Amount;
                                        existingDetail.TaxRate = detailDto.TaxRate;
                                        existingDetail.TaxAmount = detailDto.TaxAmount;
                                        existingDetail.Remarks = detailDto.Remarks;
                                        existingDetail.UpdateTime = DateTime.Now;
                                        detailsToUpdate.Add(existingDetail);
                                    }
                                }
                            }
                            else if (!detailDto.IsDelete)
                            {
                                // 添加新明细
                                var newDetail = new SalesInvoiceDetail
                                {
                                    InvoiceId = request.InvoiceId,
                                    ProductName = detailDto.ProductName,
                                    Specifications = detailDto.Specification,
                                    Unit = detailDto.Unit,
                                    Quantity = detailDto.Quantity,
                                    UnitPrice = detailDto.UnitPrice,
                                    Amount = detailDto.Amount,
                                    TaxRate = detailDto.TaxRate,
                                    TaxAmount = detailDto.TaxAmount,
                                    Remarks = detailDto.Remarks,
                                    CreateTime = DateTime.Now,
                                    UpdateTime = DateTime.Now,
                                    CreateName = request.UpdateName,
                                    UpdateName = request.UpdateName,
                                    isDel = false
                                };

                                detailsToAdd.Add(newDetail);
                            }
                        }

                        // 批量更新明细
                        if (detailsToUpdate.Count > 0)
                        {
                            var updateDetailsResult = await _salesInvoiceDetailRepository.UpdateRange(detailsToUpdate);
                            if (updateDetailsResult < detailsToUpdate.Count)
                            {
                                return new APIRequst<bool> { Code = RequstCode.失败, Msg = "部分明细更新失败" };
                            }
                        }

                        // 批量添加明细
                        if (detailsToAdd.Count > 0)
                        {
                            var addDetailsResult = await _salesInvoiceDetailRepository.AddRange(detailsToAdd);
                            if (addDetailsResult < detailsToAdd.Count)
                            {
                                return new APIRequst<bool> { Code = RequstCode.失败, Msg = "部分明细添加失败" };
                            }
                        }
                    }
                    tran.Complete();
                    // 修正：成功时返回RequstCode.成功
                    return new APIRequst<bool> { Code = RequstCode.成功, Data = true, Msg = "更新成功" };
                  
                }
                catch (Exception ex)
                {
                    // 记录异常并返回失败结果，包含完整异常信息
                    return new APIRequst<bool> { Code = RequstCode.失败, Msg = $"更新失败：{GetFullExceptionMessage(ex)}" };
                }
            }
                
        }

        /// <summary>
        /// 获取完整的异常信息，包括内部异常
        /// </summary>
        /// <param name="ex">异常对象</param>
        /// <returns>完整的异常信息字符串</returns>
        private string GetFullExceptionMessage(Exception ex)
        {
            var message = ex.Message;
            var innerException = ex.InnerException;
            while (innerException != null)
            {
                message += $" 内部异常：{innerException.Message}";
                innerException = innerException.InnerException;
            }
            return message;
        }
    }
}